using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;

namespace Super
{
	[RequireComponent(typeof(TextMeshProUGUI))]
	public class TypeWriter : MonoBehaviour, ILangRefresh
	{
		/// <summary>
		/// 加粗，倾斜，颜色，大小, 链接, 下划线,结尾符
		/// </summary>
		private List<string> richFormats = new List<string>() { "<b>", "<i>", "<color", "<size", "<link", "<u>", "</" };
		private char richEndSign = '>';
		private TextMeshProUGUI TMP_text;
		private TextMeshProUGUI TMP_Text
		{
			get
			{
				if (TMP_text == null)
				{
					TMP_text = GetComponent<TextMeshProUGUI>();
				}
				return TMP_text;
			}
		}
		private string typeText;
		private IEnumerator typeIterator;
		private TypeWriteState typeState = TypeWriteState.UnStart;
		private Action callBack;

		private string key = "";
		private List<object> args = new List<object>();

		/// <summary>
		/// 获取打印机状态
		/// </summary>
		/// <returns></returns>
		public TypeWriteState GetState()
		{
			return typeState;
		}

		/// <summary>
		/// 开始打印文本
		/// </summary>
		/// <param name="text"></param>
		/// <param name="params_interval"></param>
		private void StartTypingText(string text)
		{
			CancelTyping();
			this.typeText = text;
			typeIterator = TypingCo();
			StartCoroutine(typeIterator);
			typeState = TypeWriteState.Doing;
		}

		/// <summary>
		/// 打印不需要翻译的对象，数字等，不要打印文本，会影响多语言功能
		/// </summary>
		/// <param name="obj"></param>
		public void StartTyping(object obj)
		{
			CancelTyping();
			key = "";
			this.typeText = obj.ToString();
			typeIterator = TypingCo();
			StartCoroutine(typeIterator);
			typeState = TypeWriteState.Doing;
		}

		/// <summary>
		/// 打印多语言
		/// </summary>
		/// <param name="key"></param>
		public void StartTypingByKey(string key)
		{
			List<object> list = new List<object>();
			StartFormatTyping(key, list);
		}

		/// <summary>
		/// 打印格式化多语言
		/// </summary>
		/// <param name="key"></param>
		/// <param name="arg0"></param>
		public void StartFormatTyping(string key, params object[] args)
		{
			List<object> list = new List<object>(args);
			StartFormatTyping(key, list);
		}

		public void StartFormatTyping(string key, List<object> args)
		{
			string content = LangManager.Ins.GetText(key);
			content = string.Format(content, args);
			this.key = key;
			this.args = args;
			StartTypingText(content);
		}

		/// <summary>
		/// 刷新多语言文本
		/// </summary>
		public void OnLangRefresh()
		{
			if (!string.IsNullOrEmpty(key))
			{
				ForceFinishTyping();
				string content = LangManager.Ins.GetText(key);
				content = string.Format(content, args);
				typeText = content;
				TMP_Text.text = content;
			}
		}

		/// <summary>
		/// 打字完成触发回调
		/// </summary>
		public void OnFinishTyping()
		{
			typeState = TypeWriteState.Finished;
			TMP_Text.text = typeText;
			callBack?.Invoke();
		}

		/// <summary>
		/// 取消打印文本
		/// </summary>
		public void CancelTyping()
		{
			if (typeIterator != null)
			{
				StopCoroutine(typeIterator);
			}
		}

		/// <summary>
		/// 强制完成打印文本
		/// </summary>
		public void ForceFinishTyping()
		{
			if (GetState() == TypeWriteState.Finished)
			{
				return;
			}
			CancelTyping();
			OnFinishTyping();
		}

		/// <summary>
		/// 设置结束回调
		/// </summary>
		/// <param name="action"></param>
		public void SetFinishCallBack(Action action)
		{
			callBack = action;
		}

		/// <summary>
		///打字异步操作
		/// </summary>
		/// <returns></returns>
		private IEnumerator TypingCo()
		{
			int tempIndex = 0, subWordsLen = 0;
			string subWords = "";
			StringBuilder SB = new StringBuilder();

			for (int i = 0; i < typeText.Length;)
			{
				bool isRich = CheckIsRichText(typeText, i);
				tempIndex = i + 1;
				while (isRich)
				{
					tempIndex = GetRichEndIndex(typeText, tempIndex);
					tempIndex += 1;
					isRich = CheckIsRichText(typeText, tempIndex);
				}

				subWordsLen = tempIndex - i;
				subWords = typeText.Substring(i, subWordsLen);
				SB.Append(subWords);
				TMP_Text.text = SB.ToString();
				yield return new WaitForSeconds(ValueSettingSO.Ins.typeWriterInterval);
				i += subWordsLen;
			}
			OnFinishTyping();
		}

		/// <summary>
		/// 从index索引开始，是否是富文本
		/// </summary>
		/// <param name="words">检测文本</param>
		/// <param name="index">检测开始的索引</param>
		/// <returns></returns>
		private bool CheckIsRichText(string words, int index)
		{
			if (index >= words.Length - 1)
				return false;

			string subString = words.Substring(index);
			foreach (var item in richFormats)
			{
				if (subString.StartsWith(item))
					return true;
			}
			return false;
		}

		/// <summary>
		/// 返回富文本结束的下标
		/// </summary>
		/// <param name="words">检测文本</param>
		/// <param name="index">检测开始的索引</param>
		/// <returns></returns>
		private int GetRichEndIndex(string words, int index)
		{
			for (int i = index; i < words.Length; i++)
			{
				if (words[i] == richEndSign)
					return i;
			}
			return index;
		}
	}

}
